package com.hxit.huaxiamelongarden.controller;

import com.hxit.huaxiamelongarden.domin.dto.IndexDto;
import com.hxit.huaxiamelongarden.domin.vo.IndexVo;
import com.hxit.huaxiamelongarden.service.*;
import com.hxit.huaxiamelongarden.utils.EntityUtil;
import com.hxit.huaxiamelongarden.utils.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @ClassName IndexController
 * @description 小程序首页
 * @Author 12694
 * @Date 2025/1/28 15:11
 * @Version 1.0
 **/
@Tag(name = "首页管理接口", description = "提供首页内容管理的相关功能") // 对整个控制器模块进行描述
@RestController
@RequestMapping("/index")
@Slf4j
public class IndexController {

    @Autowired
    private IndexService indexService;
    @Autowired
    private UserService userService;
    @Autowired
    private ContentService contentService;
    @Autowired
    private HotSearchService hotSearchService;
    @Autowired
    private SearchHistoryService searchHistoryService;

    /**
     * 默认显示内容接口
     *
     * @return 返回内容列表
     */
    @Operation(summary = "获取首页内容列表", description = "获取首页内容的完整列表信息")
    @GetMapping("/list")
    public Result list() {
        List<IndexVo> list = indexService.list();
        return Result.success(list);
    }
    //首页搜索
    @Operation(summary = "搜索", description = "根据不同条件搜索")
    @PostMapping("/list")
    public Result search(@RequestBody IndexDto indexDto,@RequestAttribute("userId") String userId) throws IllegalAccessException {
        searchHistoryService.addSearchHistory(Integer.parseInt(userId), (String) EntityUtil.getNonNullValues(indexDto).get(0));
        if (indexDto.getNickname()!=null||indexDto.getPhoneNumber()!=null||indexDto.getStudentId()!=null){
            log.info("根据用户搜索查找：{}",indexDto);
            List<IndexVo> indexVos = indexService.searchByUser(indexDto);
            return Result.success(indexVos);
        }
        if (indexDto.getContent()!=null||indexDto.getTitle()!=null){
            log.info("根据内容或话题搜索查找：{}",indexDto);
            if (indexDto.getTitle()!=null){
                hotSearchService.incrementHotSearch(indexDto.getTitle());
            }
            List<IndexVo> indexVos = indexService.searchByTitleOrContent(indexDto);
            return Result.success(indexVos);
        }
        if (indexDto.getTags()!=null){
            log.info("根据标签搜索查找：{}",indexDto);
            List<IndexVo> indexVos = indexService.searchByTags(indexDto);
            return Result.success(indexVos);
        }
        return Result.error("查询失败！");
    }
    //历史搜索记录
    @Operation(summary = "历史搜索记录")
    @GetMapping("/history")
    public Result historySearch(@RequestAttribute("userId") String userId){
        List<String> searchHistory = searchHistoryService.getSearchHistory(Integer.parseInt(userId));
        return Result.success(searchHistory);
    }
}
